/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("pagination");
    var util = require("util");
    var _ = require("underscore");
    require("./common");
    var Template = require("/public/js/lib/template");
    var Highcharts = require("/public/js/lib/highcharts/js/highcharts");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'commonModule']);

    // 查询服务
    function queryService($http, $q, $timeout, baseData) {
        var service = {
            // 明细周期
            detailCycle: '1',
            // 拓客对比图表周期
            compareChartCycle: '1',
            // 拓客对比明细周期
            compareDetailCycle: '1',
            // 客户状态统计汇总数据
            totalData: {},
            // 数据类型：推荐、带看 1-6
            type: '1',
            // 第二个图表类型
            type2: '1',

            // =======================数据转化 start====================================
            convertData: function (data) {

                var maxNum = 0;
                for (var i = 0; i < data.length; i++) {
                    data[i].Value = parseInt(data[i].tjjiesCount || data[i].dkjiesCount || data[i].rcCount || data[i].rgCount || data[i].qyCount || data[i].cjAmount) || 0;
                    data[i].Key = data[i].brokerName;
                    if (data[i].Value > maxNum) {
                        maxNum = data[i].Value;
                    }
                }
                if (maxNum == 0) {
                    maxNum = 1;
                }

                var custData = { topNum: data.length, data: data, maxNum: maxNum, colUnit: '' };

                return custData;
            },

            convertData2: function (data) {
                var i = 0, len = data.detail.length, temp, j,
                    custData = {
                        xLen: len,
                        data: [],
                        yLen: 0,
                        rowCount: data.rowCount
                    };

                for (; i < len; i++) {
                    var tradeDetail = data.detail[i];
                    temp = tradeDetail.data;
                    custData.yLen = Math.max(custData.yLen, temp.length);

                    for (j in tradeDetail) {
                        if (tradeDetail.hasOwnProperty(j)) {
                            if (j !== 'data') {
                                (custData[j] || (custData[j] = [])).push(tradeDetail[j]);
                            }
                        }
                    }

                    custData.data.push(temp);
                }

                return custData;
            },

            convertData3: function(data) {
                var i = 0, j, len = data.length, length = 0,
                    custData = {}, series = [], n = -1,
                    categories = [], temp, tempData;

                for (; i < len; i++) {
                    series[i] = {};
                    series[i]['name'] = data[i]['identityName'];
                    series[i]['data'] = [];
                    series[i]['color'] = baseData.colorArray[i];
                    tempData = data[i]['data'];

                    for (j = 0, length = tempData.length; j < length; j++) {
                        if (i === 0) {
                            categories.unshift(tempData[j]['xdate']);
                        }

                        series[i]['data'].unshift(parseFloat(tempData[j]['tjjiesCount'] || tempData[j]['dkjiesCount'] || tempData[j]['rcCount'] || tempData[j]['rgCount'] || tempData[j]['qyCount'] || tempData[j]['cjAmount']) || 0);
                    }
                }

                custData.step = length > 0 ? Math.ceil(length / 4) : 1;
                custData.maxStaggerLines = 1;
                custData.categories = categories;
                custData.series = series;

                return custData;
            },

            convertData4: function (data) {
                var i = 0, len = data.length,
                    custData = {}, series = [];
        
                series[0] = {};
                series[0]['data'] = [];
                for (; i < len; i++) {
                    series[0]['data'].push({
                        name: data[i]['section'],
                        y: data[i]['count'],
                        color: baseData.colorArray[i]
                    });
                }

                custData.series = series;

                return custData;
            },
            
            // =======================图表数据结构 start======================================
            dataDefault: {
                chart: {
                    type: 'area',
                    marginTop: 70
                },
                title: {
                    text: ''
                    /*text: '人数',
                    align:'left'*/
                },
                subtitle: {
                    text: '人数',
                    align: 'left'
                },
                xAxis: {
                    tickWidth: 0,
                    labels: {
                        step: 1
                    },
                    categories: []//['01-01', '01-02', '01-03', '01-04', '01-05', '01-06','01-07', '01-08', '01-10', '01-11', '01-12', '01-13']
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    min: 0,
                    minTickInterval: 1,
                    gridLineColor: '#EBEBEB',
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },
                tooltip: {
                    shared: true,
                    valueSuffix: '人'
                },
                legend: {
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true,
                    symbolWidth: 12,
                    symbolHeight: 12
                },
                plotOptions: {
                    area: {
                        stacking: null,
                        lineWidth: 1,
                        fillOpacity: 0.4
                    }
                },
                credits: { // 版权
                    enabled: false
                },
                series: []/*[{
            name: '项目1',
            color: 'red',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }, {
            name: '项目2',
            data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
        }, {
            name: '项目3',
            data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
        }, {
            name: '项目4',
            data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
        }]*/
            },

            // 不同身份拓客对比（不同身份转化率 饼图默认信息）
            dataDefaultPie: {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: 0,
                    plotShadow: false,
                    spacing: [0, 0, 0, 0]
                },
                title: {
                    text: 0 + "%",
                    align: 'center',
                    verticalAlign: 'middle',
                    style: { "fontSize": "10px" },
                    y: 5
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: false,
                        dataLabels: {
                            enabled: false
                        }
                    }
                },
                legend: {
                    verticalAlign: 'top',
                    borderWidth: 0
                },
                series: [{
                    name: '占比',
                    type: "pie",
                    innerSize: '90%',
                    data: [{
                        name: '已转化',
                        color: '#7DD3F9',
                        y: 0
                    }, {
                        name: '未转化',
                        color: '#edf8fc',
                        y: 100
                    }],
                    states: {
                        hover: {
                            enabled: false
                        }
                    }
                }]
            },

            dataDefaultSpreadPie: {
                chart: {
                    type: 'pie'
                },
                title: {
                    text: ''
                    // align:'left'
                },
                subtitle: {
                    text: ''
                },
                legend: {
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true,
                    symbolWidth: 12,
                    symbolHeight: 12
                },
                plotOptions: {
                    pie: {
                        innerSize: 100,
                        size: 200,
                        depth: 25,
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                tooltip: {
                    pointFormat: '客户数量区间{point.name}人<br>' +
                                 '经纪人数量{point.y}人<br>' +
                                 '占比{point.percentage:.2f}%'
                },
                credits: { // 版权
                    enabled: false
                },
                series: [{
                    type: 'pie',
                    name: '占比'
                    //            data: [
                    //                ['Bananas', 8],
                    //                ['Kiwi', 3]
                    //            ]
                }]
            },
        // =======================图表数据结构 end==================================

            // 统一查询，根据选择的标签页
            query: function () {
                service.queryMethod = service.queryMethod || service.queryRank;
                service.queryMethod();
            },

            // 查询经纪人个人排行榜
            queryRank: function () {
                service.queryRankNumChart();
                service.queryRankNumDetail();
                service.queryRankQualityChart();
                service.queryRankQualityDetail();
            },

            // 查询不同身份拓客对比
            queryCompare: function () {
                service.queryTuokeChart();
                service.queryTuokeDetail();
                service.queryTuokeAllProjectDetail();
                service.queryTuokeIdentity();
            },

            // 查询经纪人客户分布
            queryDistribution: function () {
                service.querySpread();
                service.querySpread2();
            },

            // 经纪人个人拓客数量：TOP 10 经纪人
            queryRankNumChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-count-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.rankNumChartData = data.data;
                    });
            },

            // 经纪人个人拓客数量：数据明细
            queryRankNumDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type;
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.rankNumDetailPageSize;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-broker-count-detail-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.rankNumDetailPageIndex = filters.pageIndex;
                        service.rankNumDetailTotal = data.data.rowCount;
                        service.rankNumDetailData = data.data;
                    });
            },

            // 导出数据
            exportRankNumDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.type = service.type;
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                var url = '/api/index.php?r=olap/regbroker-talk/export-bc-detail-info';
                util.download(url, filters);
            },

            // 经纪人个人拓客质量：TOP 10 经纪人
            queryRankQualityChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type2;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-changed-rate-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.rankQualityChartData = data.data;
                    });
            },

            // 经纪人个人拓客质量：数据明细
            queryRankQualityDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type2;
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.rankQualityDetailPageSize;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-changed-rate-detail-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.rankQualityDetailPageIndex = filters.pageIndex;
                        service.rankQualityDetailTotal = data.data.rowCount;
                        service.rankQualityDetailData = data.data.detail;
                    });
            },

            // 导出数据
            exportRankQualityDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.type = service.type2;
                var url = '/api/index.php?r=olap/regbroker-talk/export-btcr-detail-info';
                util.download(url, filters);
            },

            // 不同身份拓客对比
            queryTuokeChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.compareChartCycle = baseData.getValidCycle(service.compareChartCycle);
                filters.type = service.type;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-identity-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.tuokeChartData = data.data;
                    });
            },

            // 不同身份拓客对比数据明细
            queryTuokeDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.compareDetailCycle = baseData.getValidCycle(service.compareDetailCycle);
                filters.type = service.type;
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.tuokeDetailPageSize;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-identity-detail-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.tuokeDetailPageIndex = filters.pageIndex;
                        service.tuokeDetailTotal = data.data.rowCount;
                        service.tuokeDetailData = data.data;
                    });
            },

            // 导出数据
            exportTuokeDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.compareDetailCycle = baseData.getValidCycle(service.compareDetailCycle);
                filters.type = service.type;
                var url = '/api/index.php?r=olap/regbroker-talk/export-rti-detail-info';
                util.download(url, filters);
            },

            // 数据明细（全部项目不同身份经纪人拓客数量）
            queryTuokeAllProjectDetail: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-identity-detail-info-by-all-proj';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function(data) {
                        service.tuokeAllProjectDetailData = data.data;
                        _.each(service.tuokeAllProjectDetailData, function(record) {
                            record.data = _.sortBy(record.data, 'projName');
                        });
                    });
            },

            // 导出数据
            exportTuokeAllProjectDetail: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                var url = '/api/index.php?r=olap/regbroker-talk/export-rtiap-info';
                util.download(url, filters);
            },

            // 不同身份转化率
            queryTuokeIdentity: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-identity-changed-rate-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function(data) {
                        service.tuokeIdentityData = data.data;
                        // 转换数据
                        service.tuokeIdentityData.detail = [];
                        for (var p in service.tuokeIdentityData) {
                            if (service.tuokeIdentityData.hasOwnProperty(p)) {
                                var idx = parseInt(p);
                                if (!isNaN(idx)) {
                                    service.tuokeIdentityData.detail[idx] = service.tuokeIdentityData[p];
                                    delete service.tuokeIdentityData[p];
                                }
                            }
                        }
                    });
            },

            // 导出数据
            exportTuokeIdentity: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                var url = '/api/index.php?r=olap/regbroker-talk/export-rticr-info';
                util.download(url, filters);
            },

            // 经纪人客户分布(图表)
            querySpread: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-info-section';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.spreadData = data.data;
                        service.hasSpreadData = !!_.find(service.spreadData, function(x) {
                            return parseInt(x.count) > 0;
                        });
                    });
            },

            // 经纪人客户分布(图表)
            querySpread2: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.type2;
                var url = '/api/index.php?r=olap/regbroker-talk/get-regbroker-talk-changed-rate-section';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.spread2Data = data.data;
                        service.hasSpread2Data = !!_.find(service.spread2Data, function (x) {
                            return parseInt(x.count) > 0;
                        });
                    });
            }
        };

        return service;
    }
    app.factory('query', ['$http', '$q', '$timeout', 'baseData', queryService]);

    var route = function($routeProvider) {
        $routeProvider
            .when('/rank', {
                templateUrl: 'views/broker-quality/rank.html',
                controller: 'RankViewController'
            })
            .when('/compare', {
                templateUrl: 'views/broker-quality/compare.html',
                controller: 'CompareViewController'
            })
            .when('/distribution', {
                templateUrl: 'views/broker-quality/distribution.html',
                controller: 'DistributionViewController'
            })
            .otherwise({ redirectTo: '/rank' });
    };
    app.config(['$routeProvider', route]);

    function StatisticsController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        $scope.path = $location.path();
        $scope.changeTab = function (path) {
            $location.path(path);
            $scope.path = path;
        };
    }
    app.controller('StatisticsController', ['$scope', '$location', 'baseData', 'query', StatisticsController]);

    function SearchController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        $scope.$watch('baseData.projectIds', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.query();
            }
        });

        if (baseData.loaded) {
            query.query();
        }
    }
    app.controller('SearchController', ['$scope', '$location', 'baseData', 'query', SearchController]);

    // 经纪人个人排行榜视图控制器
    function RankViewController($scope, $location, query, baseData) {
        query.queryMethod = query.queryRank;
        query.type = '1';
        query.type2 = '1';

        if (baseData.loaded) {
            query.query();
        }

        $scope.$watch('query.detailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryRankNumDetail();
            }
        });

        $scope.$watch('query.rankNumChartData', function (newValue) {
            if (newValue !== undefined) {
                var detailData = query.convertData(newValue);
                var html = Template($('#templ_graphic_01').html(), detailData, baseData.formatData);
                $('#graphic_01').html(html);
            }
        });

        $scope.$watch('query.rankNumDetailData', function (newValue) {
            if (newValue !== undefined) {
                var data = newValue;

                data['colTitle'] = query.typeText || '推荐客户(已接收)';
                data['colUnit'] = '';
                data['pageIndex'] = query.rankNumDetailPageIndex;
                data['pageSize'] = query.rankNumDetailPageSize;
                var html = Template($('#templ_table_01').html(), data, baseData.formatData);
                $('#table_content_01').html(html);
            }
        });
    }
    app.controller('RankViewController', ['$scope', '$location', 'query', 'baseData', RankViewController]);

    // 不同身份拓客对比视图控制器
    function CompareViewController($scope, $location, query, baseData) {
        query.queryMethod = query.queryCompare;
        query.type = '1';
        query.type2 = '1';

        if (baseData.loaded) {
            query.query();
        }

        $scope.$watch('query.compareChartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryTuokeChart();
            }
        });

        $scope.$watch('query.compareDetailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryTuokeDetail();
            }
        });

        $scope.$watch('query.tuokeChartData', function (newValue, oldValue) {
            if (newValue !== undefined && newValue !== oldValue) {
                var data = query.convertData3(newValue);

                if (query.type == '6') {
                    query.dataDefault.subtitle.text = "金额（元）";
                    query.dataDefault.tooltip.valueSuffix = '元';
                } else {
                    query.dataDefault.subtitle.text = "人数";
                    query.dataDefault.tooltip.valueSuffix = '人';
                }

                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault, {
                    chart: {
                        renderTo: 'graphic_03'
                    },
                    xAxis: {
                        categories: data.categories,
                        labels: {
                            step: data.step
                        }
                    },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.tuokeDetailData', function (newValue, oldValue) {
            if (newValue !== undefined && newValue !== oldValue) {
                var data = query.convertData2(newValue);
                var html = Template($('#templ_table_03_' + query.type).html(), data, baseData.formatData);
                $('#table_content_03').html(html);
            }
        });

        $scope.$watch('query.tuokeAllProjectDetailData', function (newValue, oldValue) {
            if (newValue !== undefined && newValue !== oldValue) {
                var data = query.convertData2({ detail: newValue });
                var html = Template($('#templ_table_04').html(), data, baseData.formatData);
                $('#table_content_04').html(html);
            }
        });

        $scope.showTuokeIdentityChart = function (index) {
            $scope.tuokeIdentityChartIndex = index;

            var curData = {};
            var temp = query.tuokeIdentityData.detail[index];
            if (!temp) {
                return;
            }

            curData.num_tj = parseFloat(temp.tjjiesCount);
            curData.num_dk = parseFloat(temp.curDkCount);
            curData.num_rg = parseFloat(temp.curRgCount);
            curData.num_qy = parseFloat(temp.curQyCount);
            curData.rate_dk = parseFloat(temp.dk2tjRate);
            curData.rate_rg = parseFloat(temp.cj2dkRate);
            curData.rate_cj = parseFloat(temp.cj2tjRate);

            $("#p_tj").html("推荐&nbsp;&nbsp;" + curData.num_tj + "人");
            $("#p_dk").html("到访&nbsp;&nbsp;" + curData.num_dk + "人");
            $("#p_rg").html("认购（含直签）&nbsp;&nbsp;" + curData.num_rg + "人");
            $("#p_qy").html("签约&nbsp;&nbsp;" + curData.num_qy + "人");

            $('#pie_rate_dk').highcharts($.extend(true, {}, query.dataDefaultPie, {
                title: {
                    text: curData.rate_dk + "%"
                },
                series: [{
                    data: [{
                        y: curData.rate_dk
                    }, {
                        y: 100 - curData.rate_dk
                    }]
                }],
                credits: { // 版权
                    enabled: false
                }
            }));

            setTimeout(function () {
                $('#pie_rate_dk').highcharts().reflow();
            }, 0);

            $('#pie_rate_rg').highcharts($.extend(true, {}, query.dataDefaultPie, {
                title: {
                    text: curData.rate_rg + "%"
                },
                series: [{
                    data: [{
                        y: curData.rate_rg
                    }, {
                        y: 100 - curData.rate_rg
                    }]
                }],
                credits: { // 版权
                    enabled: false
                }
            }));

            setTimeout(function () {
                $('#pie_rate_rg').highcharts().reflow();
            }, 0);

            $('#pie_rate_cj').highcharts($.extend(true, {}, query.dataDefaultPie, {
                title: {
                    text: curData.rate_cj + "%"
                },
                series: [{
                    data: [{
                        y: curData.rate_cj
                    }, {
                        y: 100 - curData.rate_cj
                    }]
                }],
                credits: { // 版权
                    enabled: false
                }
            }));

            setTimeout(function () {
                $('#pie_rate_cj').highcharts().reflow();
            }, 0);
        };

        $scope.$watch('query.tuokeIdentityData', function (newValue, oldValue) {
            if (newValue !== undefined && newValue !== oldValue) {
                $scope.showTuokeIdentityChart(0);
                // 明细数据
                var data = newValue;
                var html = Template($('#templ_table_05').html(), data, baseData.formatData);
                $('#table_content_05').html(html);
            }
        });
    }
    app.controller('CompareViewController', ['$scope', '$location', 'query', 'baseData', CompareViewController]);

    // 经纪人客户分布视图控制器
    function DistributionViewController($scope, $location, query, baseData) {
        query.queryMethod = query.queryDistribution;
        query.type = '1';
        query.type2 = '1';

        if (baseData.loaded) {
            query.query();
        }

        $scope.$watch('query.spreadData', function (newValue) {
            if (newValue !== undefined) {
                var data = newValue;
                var unit = '人', type = '客户数量区间';
                if (query.type == '6') {
                    unit = '元';
                    type = '认购金额';
                }
                else if (query.type == '7') {
                    unit = '元';
                    type = '签约金额';
                }

                // 明细
                var html = Template($('#templ_table_spread').html(), { detail: data, type: type }, baseData.formatData);
                $('#table_content_spread').html(html);
                // 图表
                data = query.convertData4(newValue);

                query.dataDefaultSpreadPie.tooltip.pointFormat = type + '{point.name}' + unit + '<br>' +
                                                         '经纪人数量{point.y}人<br>' +
                                                         '占比{point.percentage:.2f}%';
                var chart = new Highcharts.Chart($.extend(true, {}, query.dataDefaultSpreadPie, {
                    chart: { renderTo: 'graphic_spread' },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.spread2Data', function (newValue) {
            if (newValue !== undefined) {
                var data = newValue;
                // 明细
                var html = Template($('#templ_table_spread2').html(), { detail: data }, baseData.formatData);
                $('#table_content_spread_02').html(html);
                // 图表
                data = query.convertData4(newValue);
                var type = '推荐转到访';
                switch (query.type2) {
                    case '1':
                        type = '推荐转到访';
                        break;
                    case '2':
                        type = '到访转认购（含直签）';
                        break;
                    case '3':
                        type = '推荐转签约';
                        break;
                    default:
                }

                query.dataDefaultSpreadPie.tooltip.pointFormat = type + '{point.name}<br>' +
                                                           '经纪人数量{point.y}人<br>' +
                                                           '占比{point.percentage:.2f}%';
                var chart = new Highcharts.Chart($.extend(true, {}, query.dataDefaultSpreadPie, {
                    chart: { renderTo: 'graphic_spread_02' },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });
    }
    app.controller('DistributionViewController', ['$scope', '$location', 'query', 'baseData', DistributionViewController]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});